const RankInfo = function () {
    // 通用于排行数据的结构体样式.
    this.rank = null;
    this.avatar = null;
    this.nickname = null;
    this.openid = null;
    this.gender = 0;
    // data 用于自定义的排行数据对象.
    this.data = null;
};

const Common = {
    // 获取当前的星期数.
    getFullWeeks: function (timestamp) {
        // 1970-1-1是周四. 距离下个周日有3天.259200000,时间戳是以08:00开始的,再校正一下,+8时区.
        let weeks = Math.floor((timestamp - 230400000) / 604800000);
        return weeks;
    },

    //获取当前月数.
    getMonths: function (timestamp) {
        if (!timestamp) timestamp = Date.now();
        let date = new Date();
        date.setTime(timestamp);
        return date.getUTCMonth()
    },

    // 获取当前年份.
    getYears: function (timestamp) {
        if (!timestamp) timestamp = Date.now();
        let date = new Date();
        date.setTime(timestamp);
        return date.getUTCFullYear()
    },

    // 判断当前星期数是否相等.
    isSameWeek: function (time1, time2) {
        if (!time1 || !time2) return false;
        return this.getFullWeeks(time1) === this.getFullWeeks(time2)
    },

    // 判断当前月数是否相等.
    isSameMonth: function (time1, time2) {
        if (!time1 || !time2) return false;
        const d1 = new Date();
        const d2 = new Date();
        d1.setTime(time1);
        d2.setTime(time2);
        return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
    }
};

const RankUtil = {
    // 获取某key对应的排行数据,可根据dateFilter进行过滤处理.
    getRankData: function (key, sortKey) {
        return new Promise(resolve => {
            wx.getFriendCloudStorage({
                keyList: [key],
                success: res => {
                    console.log('wx.getFriendCloudStorage success:', res);
                    let datas = res.data;
                    let ranks = [];
                    if (!datas || datas.length <= 0) {
                        console.log("排行榜数据为空===");
                        return [];
                    }
                    // 这里并未进行数据排序.
                    let rankIndex = 0;
                    let todayMills = Date.now();
                    // let up_times;

                    datas = this.sortFunction(datas, sortKey);
                    for (let item of datas) {
                        if (item.KVDataList.length <= 0) {
                            continue;
                        }
                        let rankCloud = JSON.parse(item.KVDataList[0].value);
                        // up_times = rankCloud["timestamp"];
                        // if (!up_times) {
                        //     console.error("排行榜数据过滤失败, 请使用Wx.updateUserData()接口进行排行榜更新.")
                        //     continue;
                        // }

                        // if (!this.filterData(todayMills, up_times, dateFilter)) {
                        //     continue;
                        // }

                        let rank = new RankInfo();
                        rank.rank = rankIndex++;
                        rank.nickname = item.nickname;
                        rank.avatar = item.avatarUrl;
                        rank.openid = item.openid;
                        rank.data = rankCloud;
                        ranks.push(rank);
                    }
                    resolve(ranks);
                },
                fail: res => {
                    console.error('wx.getFriendCloudStorage fail', res);
                    resolve([]);
                }
            })
        })
    },

    sortFunction(dataList, sortKey) {
        if (sortKey === "heroNum") {
            sortKey = "score";
        }

        dataList.sort(function (itemA, itemB) {
            if (itemA.KVDataList[0] && itemA.KVDataList[0].length === 0) {
                return 1;
            } else if (itemB.KVDataList[0] && itemB.KVDataList[0].length === 0) {
                return -1;
            }

            let data1 = itemA.KVDataList[0].value;
            let data2 = itemB.KVDataList[0].value;
            data1 = JSON.parse(data1);
            data2 = JSON.parse(data2);
            if (null === data1[sortKey] || undefined === data1[sortKey]) {
                let wxgame1 = data1['wxgame'];
                let wxgame2 = data2['wxgame'];
                if (null === wxgame2 || undefined === wxgame2) {

                } else {
                    if (wxgame1[sortKey] !== wxgame2[sortKey]) {
                        return wxgame2[sortKey] - wxgame1[sortKey];
                    } else {
                        return wxgame1['update_time'] - wxgame2["update_time"]; //时间越小 
                    }
                }
            } else {
                if (data1[sortKey] !== data2[sortKey]) {
                    return data2[sortKey] - data1[sortKey];
                } else {

                }
            }
        });

        return dataList;
    },


    // 根据某key 进行数据排序.
    sortData: function (dataList, sortKey) {
        if (!dataList || !sortKey) return;
        if (dataList.length <= 0) return;
        if (!dataList[0].data.hasOwnProperty(sortKey)) return;
        dataList.sort((a, b) => {
            return b.data[sortKey] - a.data[sortKey];
        });
        for (let i = 0; i < dataList.length; i++) {
            dataList[i].rank = i;
        }
    },

    // 是否根据时间进行数据过滤.
    filterData: function (t1, t2, dateFilter) {
        switch (dateFilter) {
            case 0:
                return true;
            case 1:
                { // week.
                    return Common.isSameWeek(t1, t2);
                }
            case 2:
                {
                    return Common.isSameMonth(t1, t2);
                }
        }
        return true;
    },

    // 从排行榜中过滤查找自己的排行数据,不借助openid比较.
    filterSelfData: function (dataList, selfData) {
        if (!selfData || !dataList) return;
        for (let d of dataList) {
            if (selfData["avatar"] === d["avatar"]) {
                // console.log("查找到自已的排行数据.");
                selfData.rank = d.rank == null ? 0 : d.rank;
                return;
                // selfData.nickname = d.nickname || "游客";
                // selfData.avatar = d.avatar;
                // selfData.openid = d.openid;
            }
        }
    },

    // 获取当前玩家自己的排行数据.
    getSelfData: function (key) {
        return this.getSelfUserInfo().then(userInfo => {
            const ranks = new RankInfo();
            ranks.avatar = userInfo.avatarUrl;
            ranks.nickname = userInfo.nickName;
            ranks.openid = userInfo.openid;
            ranks.gender = userInfo.gender;
            return new Promise(resolve => {
                wx.getUserCloudStorage({
                    keyList: [key],
                    success(res) {
                        console.log("获取到当前玩家的数据.", res);
                        if (res.KVDataList.length <= 0) {
                            resolve(ranks);
                            return
                        }
                        let rankCloud = JSON.parse(res.KVDataList[0].value);
                        ranks.data = rankCloud;
                        resolve(ranks);
                    },
                    fail(res) {
                        resolve(ranks);
                    }
                });
            })
        }).catch(res => {
            console.error("获取当前玩家用户信息失败.");
        });
    },

    // 获取当前玩家的个人信息, 用于无排行数据时进行显示.
    getSelfUserInfo: function () {
        return new Promise((resolve, reject) => {
            wx.getUserInfo({
                openIdList: ["selfOpenId"],
                lang: "zh_CN",
                success(res) {
                    console.log("自己的信息:", res);
                    resolve(res.data[0])
                },
                fail(res) {
                    reject(res)
                }
            })
        })
    },

};
module.exports.RankInfo = RankInfo;
module.exports.RankUtil = RankUtil;
module.exports.Common = Common;